package com.gzc.just.play.last.war.centralserver.user.repository;

import com.gzc.just.play.last.war.centralserver.user.model.User;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Optional;

/**
 * 用户数据访问接口
 * 替代C++的用户数据库操作
 */
@Repository
public interface UserRepository extends JpaRepository<User, Long> {
    
    /**
     * 根据用户名查找用户
     */
    Optional<User> findByUsername(String username);
    
    /**
     * 根据昵称查找用户
     */
    Optional<User> findByNickname(String nickname);
    
    /**
     * 根据公会ID查找所有成员
     */
    List<User> findByGuildId(Long guildId);
    
    /**
     * 查找在线用户数
     */
    long countByStatus(User.UserStatus status);
    
    /**
     * 根据排名分数查找排名前N的用户
     */
    @Query(value = "SELECT * FROM users WHERE rank_score > 0 ORDER BY rank_score DESC LIMIT :limit", 
           nativeQuery = true)
    List<User> findTopRankedUsers(@Param("limit") int limit);
    
    /**
     * 查找VIP用户
     */
    List<User> findByIsVipTrue();
    
    /**
     * 查找VIP已过期的用户
     */
    @Query("SELECT u FROM User u WHERE u.isVip = true AND u.vipExpireTime < :now")
    List<User> findExpiredVipUsers(@Param("now") LocalDateTime now);
    
    /**
     * 查找需要恢复体力的用户
     */
    @Query("SELECT u FROM User u WHERE u.power < u.maxPower AND u.lastPowerRecoverTime < :before")
    List<User> findUsersNeedsPowerRecover(@Param("before") LocalDateTime before);
    
    /**
     * 查找指定时间范围内创建的用户
     */
    List<User> findByCreateTimeBetween(LocalDateTime startTime, LocalDateTime endTime);
    
    /**
     * 查找指定等级范围的用户
     */
    List<User> findByLevelBetween(Integer minLevel, Integer maxLevel);
    
    /**
     * 查找战斗力最高的用户
     */
    @Query(value = "SELECT * FROM users ORDER BY battle_power DESC LIMIT 1", nativeQuery = true)
    Optional<User> findStrongestUser();
    
    /**
     * 查找排名前N
     */
    @Query(value = "SELECT * FROM users ORDER BY rank_score DESC LIMIT :limit", nativeQuery = true)
    List<User> findTopPlayers(@Param("limit") int limit);
}
